// The Vue build version to load with the `import` command

// (runtime-only or standalone) has been set in webpack.base.conf with an alias.

import Vue from "vue";

import App from "./App";

import ElementUI from "element-ui";

import "element-ui/lib/theme-chalk/index.css";

import router from "./router";

import store from "./store";

import "@/assets/css/style.css";

import "@/assets/fontAwesome/css/font-awesome.min.css";

import '../static/gantt/codebase/dhtmlxgantt.css'

import echarts from "echarts";

import axios from "axios";

import qs from "qs";

import { _, util } from "@/helper";

import Clipboard from 'clipboard';
var CryptoJS = require("crypto-js");

Vue.prototype.Clipboard = Clipboard;//点击按钮时复制的插件
Vue.prototype.util = util
Vue.prototype.CryptoJS = CryptoJS
// import Vant from 'vant';

// import 'vant/lib/index.css'



// Vue.use(Vant);
import VueVideoPlayer from 'vue-video-player';
import Vant from 'vant';
import 'vant/lib/index.css'
import scroll from "vue-seamless-scroll";
Vue.use(Vant);
import { HappyScroll } from "vue-happy-scroll";

// 引入css

import "vue-happy-scroll/docs/happy-scroll.css";
//md5加密
import md5 from 'js-md5';


import Print from "@/plugs/print";

import pager from "./helper/pager";

import { userPermissionApi } from './services/UserPermission'

import {

  registerMicroApps,

  runAfterFirstMounted,

  setDefaultMountApp,

  start,

  initGlobalState

} from "qiankun";

Vue.prototype.axios = axios;

Vue.prototype.qs = qs;

Vue.prototype.$echarts = echarts;

Vue.prototype.$pager = pager;

// axios.defaults.baseURL = 'http://dev_hzjw.ihibuilding.cn' // 无缝滚动

Vue.use(scroll);

// 自定义组件名

Vue.component("happy-scroll", HappyScroll);
Vue.use(ElementUI);
Vue.config.productionTip = false;

Vue.use(Print); // 注册

// Vue.use(axios);
Vue.prototype.$md5 = md5;
// 使用video播放插件
Vue.use(VueVideoPlayer)

if (window.__POWERED_BY_QIANKUN__) { //热更新

  __webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__

};
/*权限项-开始*/

// 自定义权限判断指令

Vue.directive('auth', {

  bind: (el, binding) => {

    // console.log('权限项', el, 'binding=', binding)

    // let hasAuth = store.getters.getComponentAuth(binding.value)

    // console.log(el, binding, hasAuth, 'directive')

    // if (!hasAuth && el) {

    //   el.remove()

    // }

  },

  inserted: (el, binding) => {

    let hasAuth = store.getters.getComponentAuth(binding.value)

    // console.log(el, binding, hasAuth, 'directive')

    if (!hasAuth && el) {

      el.remove()

    }

  }

});

/*权限项-结束*/



let userAuthStore = store.state.userAuth;
// let userAuthLocal = JSON.parse(window.sessionStorage.industryUserAuth || "[]");
let userAuthLocal = JSON.parse(window.localStorage.industryUserAuth || "[]");
if (userAuthStore.length === 0) {

  store.dispatch("setUserAuth", userAuthLocal);

  // console.log('999-userAuthStore=', userAuthStore)

}



router.beforeEach(async (to, from, next) => {

  // console.log(to, "router");

  // 如果携带参数，将参数拼接上，用于处理路由相同参数不同的情况

  let query = '?'

  let queryList = []

  let keys = Object.keys(to.query)

  let path = to.path


  if (keys.length > 0) {

    for (let key of keys) {

      queryList.push(`${key}=${to.query[key]}`)

    }

    query += queryList.join('&')

    path += query

  }

  store.dispatch("setActiveTab", path);

  if (to.path !== "/home") {

    getPageAuth(from);

  }
  next();

});


// 页面跳转时获取目标页面的权限

let getPageAuth = (from) => {

  let userAuth = store.state.userAuth

  let pageAuth = {}

  let targetPage = store.state.activeTab

  // console.log(userAuth, targetPage, 'get page auth')

  getAuth(userAuth)

  function getAuth (authList) {

    authList.map((item) => {

      if (item.object_module === targetPage) {

        pageAuth = item

      } else if (item.children_list) {

        getAuth(item.children_list)

      }

    })

  }

  // console.log(pageAuth, 'page auth')

  store.dispatch('getPageAuth', pageAuth)

  // if (Object.keys(pageAuth).length === 0 && from.path !== '/home') {

  //   router.push({

  //     path: '/home'

  //   })

  // }

}

// 页面大小变化时判断是否需要折叠左侧菜单

let appDom = document.getElementsByTagName("body")[0];
let toggleLeftNav = () => {

  let width = appDom.getBoundingClientRect().width;

  if (width < 992) {

    store.dispatch("setLeftNavCollapse", true);

  } else {

    store.dispatch("setLeftNavCollapse", false);

  }

  if (width < 768) {

    store.dispatch("setLeftNavHidden", true);

  } else {

    store.dispatch("setLeftNavHidden", false);

  }

  store.dispatch("getPageSize", appDom.getBoundingClientRect());

};

// function receiveMessage (event) {

//   console.log(event, event.data, "get message");

//   if (event.origin === "http://localhost:8081") {

//     console.log("222");

//     window.sessionStorage.setItem("access_token", event.data);

//     event.source.postMessage('get token', event.origin)

//   }

// }

// window.addEventListener("message", receiveMessage, false);



window.addEventListener(

  "resize",

  _.throttle(() => {

    toggleLeftNav();

  }, 100)

);

toggleLeftNav();



// 注册监听机，监听子系统消息
// pager.subscribe(v => {
//   console.log("子系统消息", v);
//   if (v.action === "chooseLat") {
//     store.dispatch("setChooseLatVisible", true);
//   }
//   if (v.action === 'setActiveTabs') {
//     store.dispatch('setActiveTabs', v.data.nav)
//   }
// });
// 传递给子系统的消息

let message = {

  data: store.getters,
};



// 物料收发存微前端路径

let storeMicro = "";

if (process.env.NODE_ENV === "development") {
  storeMicro = "//localhost:8086";
} else {

  storeMicro = process.env.STOREMICRO_URL;

  // storeMicro = "//localhost:8083";

}
// 智慧工地微前端路径

let intecons = "";

if (process.env.NODE_ENV === "development") {
  intecons = "//localhost:8088";
} else {

  intecons = process.env.INTECONS_URL;

  // intecons = "//localhost:8083";

}



// 地磅微前端路径

let entry = "";

if (process.env.NODE_ENV === "development") {

  entry = "//localhost:8082";

} else {

  entry = process.env.BALANCE_URL;

}

// 回弹仪微前端路径

let hammerEntry = "";

if (process.env.NODE_ENV === "development") {

  hammerEntry = "//localhost:8001";

} else {

  hammerEntry = process.env.HAMMER_URL;

}

//协会监管平台前端路径

let assEntry = "";

if (process.env.NODE_ENV === "development") {
  assEntry = "//localhost:8083";
} else {

  assEntry = process.env.ASS_URL;
}

//智慧评分系统前端路径

let evaSystem = "";

if (process.env.NODE_ENV === "development") {

  evaSystem = "//localhost:8084";

} else {

  evaSystem = process.env.EVA_URL;

}
//劳务积分系统
let scoreSystem = "";
if (process.env.NODE_ENV === "development") {
  scoreSystem = "//localhost:8085";
} else {
  scoreSystem = process.env.SCORE_URL;
}

//劳务平台前端路径
let labor = "";
if (process.env.NODE_ENV === "development") {
  labor = "//localhost:8083";
} else {
  labor = process.env.LABOR_URL;
}

// 注册微前端

registerMicroApps(

  [

    {

      name: "storeMicro",

      entry: storeMicro,

      container: "#storeMicro-container",

      activeRule: "/storeMicro",

      props: message

    },

    {

      name: "intecons",

      entry: intecons,

      container: "#intecons-container",

      activeRule: "/intecons",

      props: message

    },

    {

      name: "balance",

      entry: entry,

      container: "#vue-container",

      activeRule: "/balance"

    },

    // 智慧工地评价系统

    {

      name: "eva",

      entry: evaSystem,

      container: "#eva-container",

      activeRule: "/eva"
    }, // 劳务积分系统 8085
    {
      name: "score",
      entry: scoreSystem,
      container: "#score-container",
      activeRule: "/score"
    },

    {

      name: "hammer",

      entry: hammerEntry,

      container: "#hammer-container",

      activeRule: "/hammer",

      props: {

        data: {

          choosedProject: store.state.choosedProject

        }

      }

    },

    {

      name: "ass",

      entry: assEntry,

      container: "#ass-container",

      activeRule: "/ass",

      props: message

    },

    //建工劳务平台
    {
      name: "labor",
      entry: labor,
      container: "#conlabor-container",
      activeRule: "/labor",
      props: message
    },
  ],

  {

    beforeLoad: [

      app => {

        console.log("[LifeCycle] before load %c%s", "color: green;", app.name);

      }

    ],

    beforeMount: [

      app => {

        console.log("[LifeCycle] before mount %c%s", "color: green;", app.name);

      }

    ],

    afterUnmount: [

      app => {

        console.log(

          "[LifeCycle] after unmount %c%s",

          "color: green;",

          app.name

        );

      }

    ]

  }

);

let state = {

  project: {

    proejct_id: 1,

    project_name: "测试"

  }

};

const actions = initGlobalState(state);

actions.setGlobalState(state);

// onGlobalStateChange((value, prev) => {

//   // setGlobalState({ project: { id: 1, name: 'yeqiang' } })

//   console.log('[onGlobalStateChange - master]:', value, prev)

// }

// )

// setGlobalState({

//   ignore: 'master',

//   user: {

//     name: 'master'

//   }
// })

// setDefaultMountApp('/vue')

start({

  // fetch (url, ...args) {

  //   console.log(url, ...args, "start");

  //   if (url.indexOf("map") >= 0) {

  //     // 判断是否已插入脚本

  //     let hasAppend = false;

  //     let dom = document.querySelector(".mapApiScript");

  //     if (dom && dom.src !== "") {

  //       hasAppend = true;

  //     }

  //     console.log(hasAppend, "has append");

  //     if (!hasAppend) {

  //       var head = document.getElementsByTagName("head")[0];

  //       var script = document.createElement("link");

  //       script.type = "text/javascript";

  //       script.href = url;

  //       script.class = "mapApiScript";

  //       head.appendChild(script);

  //     }

  //     // return ''

  //   }

  //   return window.fetch(url, ...args);

  // }

});



runAfterFirstMounted(() => {

  console.log("[MainApp] first app mounted");

});



/* eslint-disable no-new */

new Vue({

  el: "#hibuilding-app",

  router,

  store,

  components: {

    App

  },

  template: "<App/>"

});